package org.simplextensions.registry.phaselisteners;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.simplextensions.Utils;
import org.simplextensions.registry.Extension;
import org.simplextensions.registry.ExtensionPoint;
import org.simplextensions.registry.IExtensionRegistry;
import org.simplextensions.registry.exceptions.ExtensionsConfigurationException;

public class DefaultExtensionClassStructurePhaseListener extends APhaseListener implements IRegisterPhaseListener {

	private final static Log log = LogFactory.getLog(DefaultExtensionClassStructurePhaseListener.class);

	@Override
	public void processExtensionPoint(ExtensionPointEvent extensionPointEvent) {
		ExtensionPoint extensionPoint = extensionPointEvent.getExtensionPoint();
		IExtensionRegistry extensionRegistry = extensionPointEvent.getExtensionRegistry();

		for (Class<?> defaultExtensionClass : extensionPoint.getDefaultExtensionClasses())
			if (defaultExtensionClass != null && !defaultExtensionClass.equals(void.class)) {
				for (ExtensionPoint ep : extensionRegistry.getExtensionPointsMD()) {
					if (ep != extensionPoint && ep.getDefaultExtensionClasses() != null
							&& ep.getDefaultExtensionClasses().contains(defaultExtensionClass))
						throw new ExtensionsConfigurationException("multiply extension points:" + extensionPoint.getId() + "," + ep.getId()
								+ " confgured with the same default extension class");
				}
			}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seeorg.simplextensions.metadata.IConstructionStrutureListener#
	 * processExtension(org.simplextensions .metadata.Extension)
	 */
	@Override
	public void processExtension(ExtensionEvent extensionEvent) {
		Extension extension = extensionEvent.getExtension();
		IExtensionRegistry extensionRegistry = extensionEvent.getExtensionRegistry();

		for (ExtensionPoint ep : extensionRegistry.getExtensionPointsMD()) {
			for (Class<?> c : ep.getDefaultExtensionClasses())
				if (c.isAssignableFrom(extension.getClazz())) {
					log.trace("registering extension: " + extension.getId() + " with extension point: " + ep.getId());
					extension.setDepends(Utils.merge(extension.getDepends(), ep.getId()));
					extensionRegistry.registerExtension(ep, extension);
					return;
				}
		}
	}
}